package socketdemo.io;

import java.io.*;
import java.net.Socket;

/**
 * @author zoush
 * @createTime 2024/12/03  17:14
 */
public class ClientDemo {
    public static void main(String[] args) {
        final String DEFAULT_SERVER_HOST = "127.0.0.1";
        final int DEFAULT_SERVER_PORT = 8888;
        try (Socket socket = new Socket(DEFAULT_SERVER_HOST, DEFAULT_SERVER_PORT)){
            //接受消息
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            //发送消息
            BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));

            //获取输入消息
            BufferedReader consoleReader = new BufferedReader(new InputStreamReader(System.in));

            String msg = null;
            //循环的话客户端就可以一直输入消息，不然执行完try catch会自动释放资源，也就是断开连接

            while (true){
                String input = consoleReader.readLine();
                bufferedWriter.write(input+"\n");
                bufferedWriter.flush();
                msg = bufferedReader.readLine();
                System.out.println(msg);
                if (input.equals("exit")){
                    break;
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
